package br.urca.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import br.urca.dao.BiReservasDAO;
import br.urca.model.BiReservas;

@Transactional
public class JPABiReservasDAO implements BiReservasDAO {
	
	private EntityManager manager;
	
	public JPABiReservasDAO() {
		this(null);
	}
	
	@Inject
	public JPABiReservasDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public List<BiReservas> getListPorAluno(String matricula) {
		try {
			return this.manager
					.createQuery(
							"SELECT b FROM BiReservas b WHERE b.matriculaAluno = :matricula ",
							BiReservas.class)
					.setParameter("matricula", matricula).getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<BiReservas> getListPorFuncionario(String matricula) {
		try {
			return this.manager
					.createQuery(
							"SELECT b FROM BiReservas b WHERE b.matriculaFuncionario = :matricula ",
							BiReservas.class)
					.setParameter("matricula", matricula).getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public BiReservas getPorCodigoReserva(String codReserva) {
		try {
			return this.manager
					.createQuery(
							"SELECT b FROM BiReservas b WHERE b.codReserva = :codReserva ",
							BiReservas.class)
					.setParameter("codReserva", codReserva).getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}
	
	@Override
	public BiReservas salvar(BiReservas reserva) {
		try {
			BiReservas b = reserva;
			gerarCodReserva(b);
			this.manager.merge(b);
			return b;
		} catch(Exception e) {
			return null;
		}
	}
	
	public void gerarCodReserva(BiReservas reserva) {		
		String codigo = (String) this.manager.createQuery("SELECT MAX(b.codReserva) FROM BiReservas b").getSingleResult();
		Long id = Long.valueOf(codigo);
		id++;
		reserva.setCodReserva(String.valueOf(id));
	}

}
